package com.booktrade.controller;

import com.booktrade.entity.Books;
import com.booktrade.entity.OrderItems;
import com.booktrade.entity.Orders;
import com.booktrade.mapper.BooksMapper;
import com.booktrade.mapper.OrdersMapper;
import com.booktrade.result.Result;
import com.booktrade.service.IOrderItemsService;
import com.booktrade.vo.OrderItemVO;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 订单详情表，存储订单中包含的每本书籍的信息 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/orderItems")
@RequiredArgsConstructor
public class OrderItemsController {
    private final IOrderItemsService orderItemsService;
    private final BooksMapper booksMapper;
    private final OrdersMapper ordersMapper; // 注入 OrdersMapper

    @GetMapping("/list")
    @Operation(summary = "获取订单详情")
    public Result<List<OrderItemVO>> list(@RequestParam("orderIds") List<Integer> orderIds) {
        List<OrderItemVO> orderItemVOs = new ArrayList<>();

        for (Integer orderId : orderIds) {
            List<OrderItems> orderItems = orderItemsService.lambdaQuery().eq(OrderItems::getOrderId, orderId).list();

            // 获取订单状态
            Orders order = ordersMapper.selectById(orderId); // 根据订单ID查询订单
            String orderStatus = order != null ? order.getStatus() : "未知"; // 获取订单状态，默认“未知”

            // 获取书籍信息
            for (OrderItems item : orderItems) {
                Books book = booksMapper.selectById(item.getBookId());
                if (book != null) {
                    OrderItemVO vo = new OrderItemVO();
                    vo.setId(item.getId());
                    vo.setOrderId(item.getOrderId());
                    vo.setBookId(item.getBookId());
                    vo.setTitle(book.getTitle());
                    vo.setAuthor(book.getAuthor());
                    vo.setPrice(item.getPrice());
                    vo.setQuantity(item.getQuantity());
                    vo.setImageUrl(book.getImageUrl());
                    orderItemVOs.add(vo);
                }
            }

            // 在每个 OrderItemVO 中添加订单状态信息
            for (OrderItemVO vo : orderItemVOs) {
                vo.setOrderStatus(orderStatus); // 假设 OrderItemVO 中增加了一个 orderStatus 字段
            }
        }

        return Result.success(orderItemVOs);
    }
}
